/**
 * 
 */
package controleur;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

import tool.Language;
import vue.MotherFrame;

/**
 * <p>
 * Application to calculate your SQ.</br>
 * Use <b>whatthefat</b>'s formula : sq=35*(0.00137*I-ln(U))+240</br>
 * 
 * @author Patrick-Edouard
 * </p>
 */
public class SQCalculator {
	
	private final static double var1=35;
	private final static double var2=0.00137;
	private final static double var3=240;
	private final static String xmlPath="listSQ.xml";
	private double sq;
	private Element root;
	
	public SQCalculator()
	{
		this.openSQList();
	}
	
	/**
	 * 
	 * @param unspend The average unspent ressources in the game
	 * @param income The average income in the game
	 * @return The SQ of this game
	 */
	public double calculSQ(double unspend, double income)
	{
		this.sq=SQCalculator.var1*((SQCalculator.var2*income)-Math.log(unspend))+SQCalculator.var3;
		return this.sq;
	}
	
	public void saveSQ(double sq)
	{
		Element thisSQ = new Element("sq");
		thisSQ.setText(sq+"");
		this.root.addContent(thisSQ);
		this.saveXML();
	}
	
	/**
	 * <p>
	 * <b>Method : saveXML</b></br>
	 * Save the XML language file at his path (defined in Language.xmlPath)
	 * <p>
	 */
	private void saveXML()
	{
	   try
	   {
	      XMLOutputter sortie = new XMLOutputter(Format.getPrettyFormat());
	      sortie.output(this.root, new FileOutputStream(SQCalculator.xmlPath));
	   }
	   catch (java.io.IOException e){}
	}
	
	public double[] getSQ()
	{
		List<Element> list = this.root.getChildren();
		double[] result = new double[list.size()];
		int i=0;
		for(Element tmp : list)
		{
			result[i] = Double.parseDouble(tmp.getText());
			i++;
		}
		
		return result;
	}
	
	/**
	 * 
	 */
	private void openSQList()
	{
		SAXBuilder sxb = new SAXBuilder();
		try {
			this.root = sxb.build(new File(SQCalculator.xmlPath)).getRootElement();
		} catch (JDOMException | IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * <p>
	 * The main function, just build a new SQCalculator instance or launch the translator tool with "lang" argument.
	 * @param args use "lang" to launch the translator tool.
	 * </p>
	 */
	public static void main(String[] args) {
		
		if(args.length == 1)
		{
			if(args[0]=="lang")
			{
				Language la = new Language();
				la.editLang();
			}
		}
		new MotherFrame();
	}

}
